// pages/search/search.js
const { getProducts } = require("../../api/product.js");

Page({
  data: {
    searchKeyword: "",
    searchResults: [],
    searchHistory: [],
    loading: false,
  },

  onLoad(options) {
    // 获取搜索关键词并解码
    const rawKeyword = options.keyword || "";
    const keyword = decodeURIComponent(rawKeyword);

    console.log("=== 搜索页面接收参数 ===");
    console.log("接收到的原始关键词:", rawKeyword);
    console.log("解码后的关键词:", keyword);
    console.log("关键词长度:", keyword.length);
    console.log(
      "关键词字符编码:",
      keyword.split("").map((c) => c.charCodeAt(0))
    );
    console.log("=========================");

    this.setData({
      searchKeyword: keyword,
    });

    // 加载搜索历史
    this.loadSearchHistory();

    // 如果有关键词，执行搜索
    if (keyword) {
      this.performSearch(keyword);
    }
  },

  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync("searchHistory") || [];
    this.setData({
      searchHistory: history,
    });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = wx.getStorageSync("searchHistory") || [];

    // 移除重复项
    history = history.filter((item) => item !== keyword);

    // 添加到开头
    history.unshift(keyword);

    // 最多保存10条
    history = history.slice(0, 10);

    wx.setStorageSync("searchHistory", history);
    this.setData({
      searchHistory: history,
    });
  },

  // 搜索输入事件
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword,
    });
  },

  // 搜索确认事件
  onSearchConfirm(e) {
    const keyword = e.detail.value;
    this.performSearch(keyword);
  },

  // 执行搜索
  async performSearch(keyword) {
    if (!keyword.trim()) {
      wx.showToast({
        title: "请输入搜索关键词",
        icon: "none",
      });
      return;
    }

    this.setData({
      loading: true,
    });

    try {
      // 确保搜索关键词是UTF-8编码
      const trimmedKeyword = keyword.trim();
      const encodedKeyword = encodeURIComponent(trimmedKeyword);
      console.log("原始关键词:", trimmedKeyword);
      console.log("编码后关键词:", encodedKeyword);

      // 调用真实的商品搜索API
      const response = await getProducts({
        spuName: trimmedKeyword, // 直接传递原始关键词，让API处理编码
        pageIndex: 1,
        pageSize: 10,
      });

      console.log("搜索API响应:", response);

      // 处理搜索结果，确保数据格式正确
      const rawResults = response?.data?.list || response?.data || [];
      const results = this.formatProductData(rawResults);

      console.log("格式化后的商品数据:", results);

      this.setData({
        searchResults: results,
      });

      // 保存搜索历史
      this.saveSearchHistory(keyword);

      // 显示搜索结果数量
      wx.showToast({
        title: `找到${results.length}个商品`,
        icon: "none",
        duration: 1500,
      });
    } catch (error) {
      console.error("搜索失败:", error);
      wx.showToast({
        title: "搜索失败，请重试",
        icon: "none",
      });

      // 搜索失败时清空结果
      this.setData({
        searchResults: [],
      });
    } finally {
      this.setData({
        loading: false,
      });
    }
  },

  // 格式化商品数据，确保与product-card组件兼容
  formatProductData(products) {
    return products.map((item, index) => ({
      id: item.id || item.spuId || index,
      spuId: item.spuId || item.id,
      spuName: item.spuName || item.name || "商品名称",
      subTitle: item.subTitle || item.description || "",
      mainImage:
        item.spuImage ||
        item.image ||
        item.mainImage ||
        "/images/default-product.png",
      unitPrice: item.spuPrice || item.price || item.unitPrice || "0.00",
      totalSales: item.salesCount || item.sales || item.totalSales || 0,
      categoryName: item.categoryName || item.category || "",
      labelName: item.labelName || item.label || "",
      skuCount: item.skuCount || 1,
      // 保留原始数据
      ...item,
    }));
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: "",
      searchResults: [],
    });
  },

  // 选择搜索历史
  selectHistory(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword,
    });
    this.performSearch(keyword);
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: "确认清空",
      content: "确定要清空搜索历史吗？",
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync("searchHistory");
          this.setData({
            searchHistory: [],
          });
        }
      },
    });
  },

  // 查看商品详情
  viewProduct(e) {
    const product = e.currentTarget.dataset.product;
    wx.navigateTo({
      url: `/pages/product/product?id=${product.id}`,
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },
});
